
package com.carsite.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.carsite.dao.ItemDao;
import com.carsite.model.Item;

public class ItemDaoHibernate extends BaseDaoHibernate implements ItemDao {

    /**
     * @see com.carsite.dao.ItemDao#getItems(com.carsite.model.Item)
     */
    public List getItems(final Item item) {
       // return getHibernateTemplate().find("from Item");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.
           */
        if (item == null) {
            return getHibernateTemplate().find("from Item");
        } else {
            // filter on properties set in the item
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(item).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Item.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.carsite.dao.ItemDao#getItem(Long itemId)
     */
    public Item getItem(final Long itemId) {
        Item item = (Item) getHibernateTemplate().get(Item.class, itemId);
        if (item == null) {
            log.warn("uh oh, item with itemId '" + itemId + "' not found...");
            throw new ObjectRetrievalFailureException(Item.class, itemId);
        }

        return item;
    }

    /**
     * @see com.carsite.dao.ItemDao#saveItem(Item item)
     */    
    public void saveItem(final Item item) {
        getHibernateTemplate().saveOrUpdate(item);
    }

    /**
     * @see com.carsite.dao.ItemDao#removeItem(Long itemId)
     */
    public void removeItem(final Long itemId) {
        getHibernateTemplate().delete(getItem(itemId));
    }

	public List getItemsByOrderId(String orderId) {
		// TODO Auto-generated method stub
		  return getHibernateTemplate().find("from Item where orderId="+orderId);
	 
	}
    
    
}
